import {FC, useEffect, useMemo, useState} from "react";
import {NavBar, NoticeBar, ShareSheet, Tabbar, Toast, WaterMark} from 'react-vant';
import {FriendsO, HomeO, WarningO, VolumeO, ShareO, Records} from '@react-vant/icons'
import {Route, Routes, useLocation, useNavigate} from "react-router-dom";
import UncompletedPage from "../UncompletedPage";
import EmptyPage from "../EmptyPage";
import Overdue from "../Overdue";
import Personage from "../Personage";
import dayjs from "../../api/dayjs";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import {ShareSheetOption} from "react-vant/es/share-sheet/PropsType";
import NoteApp from "../Notebook";

interface T {
}

interface Course {
  // 课程名
  "CourseName": string
  // 作业名
  "HWName": string;
  // 结束日期
  "EndDate": string;
  // 已提交
  "IsSubmit": string;
  // 逾期
  "OverDue": string;
}

interface OnlineTest {
  CourseName: string;
  Name: string;
  CreateName: string;
  EndDate: string;
  Status: string;
  StatusUpdateDate: string;
}

const HomePage: FC = () => {

  const [option, setOption] = useState<string>('uncompleted');

  const [props, setProps] = useState({content: '对分易'});

  const [logined, setLogined] = useState(false);

  const [jobs, setJobs] = useState<Array<Course | OnlineTest>>(JSON.parse(localStorage.getItem('jobs') as string) || []);

  const location = useLocation();

  const [visible, setVisible] = useState(false);

  const [hasClosed, setHasClosed] = useState<string>(localStorage.getItem('hasClosed') || '0');

  useEffect(() => {
    setOption(location.pathname.split('/').join(''));
  })

  // 未逾期作业
  const notOverdueData = useMemo(() =>
      jobs
        .filter(item => {
            if ("Status" in item && item.Status == '-1') {
              return false;
            }
            // 截止日期在系统时间前
            return dayjs(new Date()).isBefore(dayjs(item.EndDate, "YYYY/M/D H:m:s"))
          }
        )
        .sort(
          (a, b) =>
            dayjs(a.EndDate, "YYYY/M/D H:m:s").unix() -
            dayjs(b.EndDate, "YYYY/M/D H:m:s").unix()
        ) || [],
    [jobs]
  );
  // 已逾期作业
  const overdueData = useMemo(() =>
      jobs
        .filter(item => {
          if ("Status" in item && item.Status == '-1') {
            return true;
          }
          // 截止日期在系统时间前
          return dayjs(new Date()).isAfter(
            dayjs(item.EndDate, "YYYY/M/D H:m:s")
          );
        })
        .sort(
          (a, b) =>
            dayjs(a.EndDate, "YYYY/M/D H:m:s").unix() -
            dayjs(b.EndDate, "YYYY/M/D H:m:s").unix()
        ) || [],
    [jobs]
  );

  const navigate = useNavigate();

  const nameTurn = (enName: string): string => {
    switch (enName) {
      case 'overdue':
        return '🎐逾期作业🎐';
      case 'personage':
        return '🎲个人中心🎲';
      case 'notebook':
        return '🕊️记忆存放🕊️';
      default:
        return '🎈未做作业🎈';
    }
  }

  const handleRouteChange = (r: T) => {
    navigate(`/${r}`, {replace: true});
    setOption(r as string);
  }

  const options: Array<{ name: string; icon: string; action?: () => void; }> = [
    {
      name: '微信', icon: 'wechat', action() {
        Toast.info("暂时不可用，请稍后")
      }
    },
    {
      name: '朋友圈', icon: 'wechat-moments', action() {
        Toast.info("暂时不可用，请稍后")
      }
    },
    {
      name: '微博', icon: 'weibo', action() {
        Toast.info("暂时不可用，请稍后")
      }
    },
    {
      name: 'QQ', icon: 'qq', action() {
        Toast.info("暂时不可用，请稍后")
      }
    },
    {
      name: '复制链接', icon: 'link', action() {
        navigator.clipboard.writeText("youngya.web3v.vip")
          .then(function () {
            Toast.success("已复制到剪切板")
          })
          .catch(function (error) {
            Toast.fail(`复制内容失败:${error}`)
          });
      }
    }, {
      name: '小程序码', icon: 'weapp-qrcode', action() {
        Toast.info("暂时不可用，请稍后")
      }
    },
  ]

  const handleShare = (option: ShareSheetOption) => {
    for (const share in options) {
      if (options[share]?.action !== undefined && options[share].name === option.name) {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        options[share]?.action();
      }
    }
  }

  const navBarStyle = {
    width: '100%',
    margin: 'auto',
    position: 'fixed'
  }

  return (
    <>
      <NavBar style={navBarStyle} title={nameTurn(option)} leftArrow={null} rightText={<ShareO/>}
              onClickRight={() => setVisible(true)}/>
      {
        hasClosed === '0' &&
        <NoticeBar
          leftIcon={<VolumeO/>}
          text={logined ? '欢迎登陆' : '当前正在使用本地缓存，如要获取最新实时数据请登录'}
          mode="closeable" color="#000"
          onClose={() => {
            setHasClosed('1');
            localStorage.setItem('hasClosed', String(1));
          }}
        />
      }

      <Routes>
        <Route path="/" element={<Personage setWaterMark={setProps} setJobs={setJobs} setLogined={setLogined}/>}/>
        <Route path="/uncompleted" element={<UncompletedPage jobs={notOverdueData}/>}/>
        <Route path="/overdue" element={<Overdue jobs={overdueData}/>}/>
        <Route path="/personage"
               element={<Personage setWaterMark={setProps} setJobs={setJobs} setLogined={setLogined}/>}/>
        <Route path="/notebook" element={<NoteApp/>}/>
        <Route path="*" element={<EmptyPage/>}/>
      </Routes>

      <Tabbar value={option} onChange={handleRouteChange}>
        <Tabbar.Item icon={<WarningO/>} name={"overdue"}
                     badge={overdueData.length ? {content: overdueData.length} : undefined}>逾期作业</Tabbar.Item>
        <Tabbar.Item icon={<HomeO/>} name={"uncompleted"}
                     badge={notOverdueData.length ? {content: notOverdueData.length} : undefined}>未做作业</Tabbar.Item>
        <Tabbar.Item icon={<Records/>} name={"notebook"}>记事本</Tabbar.Item>
        <Tabbar.Item icon={<FriendsO/>} name={"personage"}>个人中心</Tabbar.Item>
      </Tabbar>

      <ShareSheet
        visible={visible}
        options={options}
        title='立即分享给好友'
        onCancel={() => setVisible(false)}
        onSelect={handleShare}
      />

      <WaterMark {...props} fullPage={true}/>


    </>
  )
}
export default HomePage;
